/**
 * @Author yinyunqi
 * @date 2018年2月1日
 * @Content 
 */
package com.yongqi.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.yongqi.model.Family;
import com.yongqi.service.FamilyService;

public class BackShiroRealm extends AuthorizingRealm{
    @Autowired
    FamilyService familyService;
    
    public BackShiroRealm() {
	super();
    }
    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRole("ADMIN");
	return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
	// 通过表单获得的账户名
    	doGetAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
	UsernamePasswordUsertypeToken backToken = (UsernamePasswordUsertypeToken) token;
	Family family = familyService.getFamilyByAccount(backToken.getUsername());
	String userType = family.getLevel();
	if (family != null && userType != "") {
	    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(family,
			family.getFamilypassword(), ByteSource.Util.bytes(family.getFamilyaccount()), // 加盐，用户account
			getName());
	    return simpleAuthenticationInfo;
	}else {
	    throw new AuthenticationException();
	}
    }
    
    
    
    
    
    
    
    
    
    
}

